package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.media.config.MinIoConfig;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.MediaFileService;
import com.xuecheng.model.PageParams;
import com.xuecheng.model.PageResult;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/9/10 8:58
 */
@Service
@Slf4j
public class MediaFileServiceImpl implements MediaFileService {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MediaFileService mediaFileService;

    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Value("${minio.bucket.files}")
    private String filesBucket;

    @Autowired
    MediaFilesMapper mediaFilesMapper;

    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

    @Override
    public UploadFileResultDto uploadFile(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath) {
        File file = new File(localFilePath);
        if (!file.exists()) {
            XueChengPlusException.cast("文件不存在");
        }
        //文件名称
        String filename = uploadFileParamsDto.getFilename();
        //文件扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        //文件mineType
        String mineType = getMineType(extension);
        //文件的md5
        String fileMd5 = getFileMd5(file);
        //文件的默认目录
        String defaultFolderPath = getDefaultFolderPath();
        //存储到minio中的对象名(带目录)
        String  objectName = defaultFolderPath + fileMd5 + extension;
        //上传到minio  String localFilePath, String mineType, String bucket, String objectName
        boolean b = addMediaFilesToMinIO(localFilePath, mineType, filesBucket, objectName);
        //文件大小
        uploadFileParamsDto.setFileSize(file.length());
        //将文件信息存储到数据库
        MediaFiles mediaFiles = mediaFileService.addMediaFilesToDb(companyId, fileMd5, uploadFileParamsDto, filesBucket, objectName);
        //准备返回数据
        UploadFileResultDto uploadFileResultDto = new UploadFileResultDto();
        BeanUtils.copyProperties(mediaFiles, uploadFileResultDto);
        return uploadFileResultDto;
    }

    /**
     *
     * @param companyId
     * @param fileMd5
     * @param uploadFileParamsDto
     * @param bucket
     * @param objectName
     * @return
     */
    @Transactional
    public MediaFiles addMediaFilesToDb(Long companyId, String fileMd5, UploadFileParamsDto uploadFileParamsDto, String bucket, String objectName) {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (mediaFiles == null){
            mediaFiles = new MediaFiles();
            //拷贝信息
            BeanUtils.copyProperties(uploadFileParamsDto,mediaFiles);
            mediaFiles.setId(fileMd5);
            mediaFiles.setFileId(fileMd5);
            mediaFiles.setCompanyId(companyId);
            mediaFiles.setUrl("/" + bucket + "/" + objectName);
            mediaFiles.setBucket(bucket);
            mediaFiles.setFilePath(objectName);
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setAuditStatus("002003");
            mediaFiles.setStatus("1");
        }
        int insert = mediaFilesMapper.insert(mediaFiles);
        if (insert<=0){
            log.error("保存文件信息到数据库失败，{}",mediaFiles.toString());
            XueChengPlusException.cast("保存信息失败");
        }
        //添加到待处理任务表
        addWaitingTask(mediaFiles);
        log.debug("保存文件信息到数据库成功,{}",mediaFiles.toString());


        return mediaFiles;
    }

    /**
     * 添加到待处理任务表
     * @param mediaFiles
     */
    private void addWaitingTask(MediaFiles mediaFiles) {

        //文件的存储路径
        String filePath = mediaFiles.getFilePath();
        //获取扩展名
        String extension = filePath.substring(filePath.lastIndexOf("."));
        //获取mineType
        String mineType = getMineType(extension);
        //判断文件类型
        if (mineType.equals("video/x-msvideo")){
            //添加到待处理任务表
            MediaProcess mediaProcessNew = new MediaProcess();
            BeanUtils.copyProperties(mediaFiles,mediaProcessNew);
            mediaProcessNew.setStatus("1"); //设置状态未处理
            mediaProcessNew.setFailCount(0);//失败次数默认为0
            mediaProcessMapper.insert(mediaProcessNew);
        }
    }

    /**
     * 将文件写入minIO
     * @param localFilePath 本地路径
     * @param mineType 类型
     * @param bucket 桶名
     * @param objectName 对象名字
     * @return
     */
    @Transactional
    public boolean addMediaFilesToMinIO(String localFilePath, String mineType, String bucket, String objectName) {
        try {
            UploadObjectArgs build = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .filename(localFilePath)
                    .contentType(mineType)
                    .build();
            minioClient.uploadObject(build);
            log.debug("上传文件到minio成功，bucket:{}objectname:{}",bucket,objectName);
            System.out.println("上传成功");
            return true;
        }catch (Exception e){
            e.printStackTrace();
            log.error("上传到minio失败，bucket:{},objectName:{},错误原因:{}",bucket,objectName,e);
        }
        return false;
    }

    private String getDefaultFolderPath() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(new Date()).replace("-", "/") + "/";
    }

    /**
     * 根据文件的的流获取md5
     *
     * @param file
     * @return
     */
    private String getFileMd5(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            String  fileMd5 = DigestUtils.md5Hex(fileInputStream);
            return fileMd5;
        } catch (Exception  e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 根据文件扩展名获得mineType
     *
     * @param extension
     * @return
     */
    public String getMineType(String extension) {
        if (extension == null) {
            extension = "";
        }
        //根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        //通用mimeType，字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }
}
